//
//  UIView+MBProgressHUD.m
//  XWKit
//
//  Created by xiaowuxiaowu on 16/3/26.
//  Copyright © 2016年 xiaowuxiaowu. All rights reserved.
//

#import "UIView+MBProgressHUD.h"
#import <objc/runtime.h>

@implementation UIView (MBProgressHUD)
static NSString const *hudKey = @"hudKey1";

-(MBProgressHUD *)getHUD{
    return objc_getAssociatedObject(self, &hudKey);
}
-(void)setHUD:(MBProgressHUD *)hud{
    objc_setAssociatedObject(self, &hudKey, hud, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(void )xw_showHUD{
    
    // dispatch_async(dispatch_get_main_queue(), ^{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
    [self setStyleHud:hud];
    [self setHUD:hud];
    //  });
    
}
-(void)setStyleHud:(MBProgressHUD *)hud{
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorWithWhite:0.1 alpha:0.8];
    hud.contentColor = [UIColor whiteColor];
    hud.margin = 31.0f;
    hud.label.numberOfLines = 0;
    
}

-(void)xw_hideHUD{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[self getHUD]hideAnimated:YES];
    });
    
}
-(void)xw_showHUDWithTitle:(NSString *)title{
    
    [self xw_showHUD];
    [self getHUD].label.text = title;
}

-(MBProgressHUD *)xw_showHUDWithProgressTitle:(NSString *)title{
    [self xw_showHUD];
    [self getHUD].label.text = title;
    [self getHUD].mode = MBProgressHUDModeAnnularDeterminate;//MBProgressHUDModeDeterminateHorizontalBar //进度条
    
    return [self getHUD];
}

-(void)xw_showHUDWorkWithProgress:(CGFloat )progress{
    [self getHUD].progress = progress;
}


static const CGFloat xw_HUDafterDelay = 1.5f;
-(void)xw_hideHUDafterDelay:(NSString *)title{
    
    
    MBProgressHUD *hud = [self getHUD];
    if(!hud){
        [self xw_showHUD];
        hud = [self getHUD];
    }
    hud.mode = MBProgressHUDModeCustomView;
    // Set an image view with a checkmark.
    UIImage *image = [[UIImage imageNamed:@"Checkmark"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    hud.customView = [[UIImageView alloc] initWithImage:image];
    // Looks a bit nicer if we make it square.
    hud.square = YES;
    // Optional label text.
    hud.label.text = title;
    hud.label.numberOfLines = 0;
    [self xw_hideAfterDelay:xw_HUDafterDelay];
    
}
-(void)xw_hideTitle:(NSString *)title{
    
    MBProgressHUD *hud = [self getHUD];
    if(!hud){
        [self xw_showHUD];
        hud = [self getHUD];
    }
    hud.label.text = title;
    hud.label.numberOfLines = 0;
    hud.mode = MBProgressHUDModeText;
    hud.animationType = MBProgressHUDAnimationZoomIn;
    //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
    [self xw_hideAfterDelay:xw_HUDafterDelay];
    
}


-(void)xw_hideAfterDelay:(CGFloat)delay{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[self getHUD] hideAnimated:YES afterDelay:delay];
        [self setHUD:nil];
    });
    
}



+(void)xw_showHUDWithTitle:(NSString *)title{
    dispatch_main_async_safe(^{
        MBProgressHUD *hud = [MBProgressHUD HUDForView:[XWCommon shareAppDelegate].window];
        if(!hud)
            hud = [MBProgressHUD showHUDAddedTo:[XWCommon shareAppDelegate].window animated:YES];
        hud.label.text = title;
        hud.mode = MBProgressHUDModeIndeterminate;
       [self setupHUD:hud];
       
        
    });
}

//隐藏
+(void)xw_hideTitle:(NSString *)title{
    
    
    dispatch_main_async_safe(^{
        MBProgressHUD *hud = [MBProgressHUD HUDForView:[XWCommon shareAppDelegate].window];
        if(!hud)
            hud = [MBProgressHUD showHUDAddedTo:[XWCommon shareAppDelegate].window animated:YES];
        hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
        hud.mode = MBProgressHUDModeText;
        hud.label.text = title;
        [self setupHUD:hud];
        [hud hideAnimated:YES afterDelay:xw_HUDafterDelay];
    });
    
}
+(MBProgressHUD *)xw_showHUDWithProgressTitle:(NSString *)title{
    
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[XWCommon shareAppDelegate].window animated:YES];
        hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
        hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
        [self setupHUD:hud];
        hud.label.text = title;
        
    return hud;
    

}
+(void)setupHUD:(MBProgressHUD *)hud{
    
    hud.animationType = MBProgressHUDAnimationZoom;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorWithWhite:0.2 alpha:0.7];
//    hud.backgroundView.color = hud.bezelView.color;
    hud.label.numberOfLines = 0;
    hud.minSize = CGSizeMake(150.0, 60.0);
    hud.margin = 30.0f;
    hud.label.textColor = TPAllBackgroundColor;
    ViewRadius(hud.bezelView, 2.0);
}


+(void)xw_hideAfterDelay:(CGFloat)delay{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        MBProgressHUD *hud = [MBProgressHUD HUDForView:[XWCommon shareAppDelegate].window];
        
        if(hud.customView){
           [(XWWaveLoadingView *)hud.customView stopLoading];
        }
        [hud hideAnimated:YES afterDelay:delay];
    });
    
}


+(void)xw_hideHUD{
    [self xw_hideAfterDelay:xw_HUDafterDelay];
}
@end






@interface XWWaveLoadingView()

@property (nonatomic,strong)CADisplayLink *displayLink;
@property (nonatomic,strong)CAShapeLayer *sinShapeLayer;
@property (nonatomic,strong)CAShapeLayer *cosShapeLayer;
@property (nonatomic,strong)UIImageView *sineImageView; //
@property (nonatomic,strong)UIImageView *cosImageView; //cos
@property (nonatomic,assign) CGFloat phase;
@property (nonatomic,assign) CGFloat maxAmplitude;

@property (nonatomic,assign)CGPoint layerPosition;

@property (nonatomic,assign)BOOL isRefresh; //是否是刷新

@end

@implementation XWWaveLoadingView

+(instancetype)waveLoadingView{
    return [[XWWaveLoadingView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
}
-(instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
      
        [self loadingSetup];
    }
    return self;
}

-(void)startLoading{
  
    [_displayLink invalidate];
    _displayLink = [CADisplayLink  displayLinkWithTarget:self selector:@selector(updateWave:)];
    [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    
    if(self.layerPosition.y != NSNotFound)
        self.sinShapeLayer.position = self.layerPosition;
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.fromValue = [NSValue valueWithCGPoint:self.sinShapeLayer.position];
    animation.toValue = [NSValue valueWithCGPoint:CGPointMake(self.sinShapeLayer.position.x, self.sinShapeLayer.position.y-self.height - 10)];
    animation.duration = 1;
    animation.repeatCount = HUGE_VALF;
    animation.removedOnCompletion = NO;
    
    [self.sinShapeLayer addAnimation:animation forKey:@"sinShapeLayer"];
    [self.cosShapeLayer addAnimation:animation forKey:@"sinShapeLayer"];
    
    
}
-(void)stopLoading{
    [_displayLink invalidate];
    [self.sinShapeLayer removeAllAnimations];
    [self.cosShapeLayer removeAllAnimations];
    self.sinShapeLayer.path = nil;
    self.cosShapeLayer.path = nil;

}

-(void)loadingSetup{
    
    _sinShapeLayer = [CAShapeLayer layer];
    _cosShapeLayer = [CAShapeLayer layer];
    
    _sinShapeLayer.frame = _cosShapeLayer.frame = CGRectMake(0, self.height, self.width, self.height);
    _sinShapeLayer.backgroundColor = _cosShapeLayer.backgroundColor = [UIColor clearColor].CGColor;
    
    UIImageView *originImageView = [[UIImageView alloc]initWithImage:[ImageNamed(@"logo1") imageWithTintColor:TP_COLOR_245]];
    
    [self addSubview:originImageView];

    
    _sineImageView = [[UIImageView alloc]initWithImage:[ImageNamed(@"logo1") imageWithTintColor:[UIColor colorWithWhite:0 alpha:0]]];
    [self addSubview:_sineImageView];
   
    
    _cosImageView = [[UIImageView alloc]initWithImage:ImageNamed(@"logo1")];
    [self addSubview:_cosImageView];
    
    originImageView.frame  = _cosImageView.frame = _sineImageView.frame = self.bounds;
    originImageView.contentMode =_cosImageView.contentMode = _sineImageView.contentMode = UIViewContentModeScaleAspectFit;
    
    //给图片抹上蒙版
    _sineImageView.layer.mask = _sinShapeLayer;
    _cosImageView.layer.mask = _cosShapeLayer;
    
   _maxAmplitude = self.height *0.3;
    
    _layerPosition = _sinShapeLayer.position;
}

-(void)updateWaveProgress:(CGFloat)progress{
    
    
    _maxAmplitude = self.height *0.1;
    [self updateWave:nil];
    _maxAmplitude = self.height *0.5;
    
    self.isRefresh = YES;
    
    CGPoint position = _layerPosition;
    
    if(position.y < 10.0)
        return;
    
    position.y =  position.y - 30*progress;
    self.sinShapeLayer.position = position;
    self.cosShapeLayer.position = position;

}
- (void)updateWave:(CADisplayLink *)displayLink
{
    
    
    self.phase += _isRefresh ? 8.0f:8.0f;
    self.sinShapeLayer.path = [self createWavePathWithType:1].CGPath;
    self.cosShapeLayer.path = [self createWavePathWithType:2].CGPath;
    
    
}


- (UIBezierPath *)createWavePathWithType:(NSInteger)pathType
{
    
    UIBezierPath *wavePath = [UIBezierPath bezierPath];
    CGFloat endX = 0;
    for (CGFloat x = 0; x < self.cosImageView.width + 1; x += 1) {
        endX=x;
        CGFloat y = 0;
        if (pathType == 1) { // 数学中的sin
            y = self.maxAmplitude * sinf(360.0 / self.cosImageView.width * (x  * M_PI / 180) * 0.3 + self.phase * M_PI/ 180) + self.maxAmplitude;
        } else {
            y = self.maxAmplitude * cosf(360.0 / self.cosImageView.width *(x  * M_PI / 180) * 0.3 + self.phase * M_PI/ 180) + self.maxAmplitude;
        }
        
        if (x == 0) {
            [wavePath moveToPoint:CGPointMake(x, y)];
        } else {
            [wavePath addLineToPoint:CGPointMake(x, y)];
        }
    }
    
    CGFloat endY = CGRectGetHeight(self.bounds) + 10;
    [wavePath addLineToPoint:CGPointMake(endX, endY)];
    [wavePath addLineToPoint:CGPointMake(0, endY)];
    
    return wavePath;
}



@end
